#include "Camera.h"
#include <sfml/Window.hpp>
#include "Scene.h"
#include "Application.h"
#include "Graphics.h"
#include "Node.h"
#include "UIText.h"

Camera::Camera(void) : mTarget(0, 0, -1)
{
}

Camera::~Camera(void)
{
}

void Camera::SetPosition( const Vector3& pos )
{
	mPosition = pos;
}

void Camera::LookAt( const Vector3& target )
{
	mTarget = target;
}

void Camera::SetViewport( const Viewport& viewport )
{
	mViewport = viewport;
}

void Camera::Render( Scene* scene, bool selectMode, int x, int y )
{
	Vector3& bgColor = scene->GetBackgroundColor();

	glClearColor(bgColor.r, bgColor.g, bgColor.b, bgColor.a);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glEnable(GL_DEPTH_TEST);

	sf::Window* window = Application::GetApplication()->GetWindow();
	int screenWidth = window->GetWidth();
	int screenHeight = window->GetHeight();

	glViewport(0, 0, screenWidth, screenHeight);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	if (selectMode)
	{
		GLint vp[4];
		glGetIntegerv(GL_VIEWPORT, vp);
		gluPickMatrix(x, y, 1, 1, vp);
	}

	gluPerspective(90, (float)screenHeight / screenHeight, 0.1, 1000);

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();

	gluLookAt(mPosition.x, mPosition.y, mPosition.z, 
		mTarget.x, mTarget.y, mTarget.z,
		0, 1, 0);

	Scene::NodeList& nodes = scene->GetNodes();

	Scene::NodeList::iterator it = nodes.begin();

	while (it != nodes.end()) {
		Node* node = *it;
		if (node->GetParent() == NULL)
		{
			(*it)->Display();
		}
		it++;
	}

	glPopMatrix();

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	if (selectMode)
	{
		GLint vp[4];
		glGetIntegerv(GL_VIEWPORT, vp);
		gluPickMatrix(x, y, 2, 2, vp);
	}

	gluOrtho2D(0, screenWidth-1, 0, screenHeight-1);

	glMatrixMode(GL_MODELVIEW);

	Scene::TextList& texts = scene->GetTexts();
	Scene::TextList::iterator it2 = texts.begin();

	while (it2 != texts.end())
	{
		UIText* text = *it2;
		text->Render();
		it2++;
	}	
}
